package com.cskaoyan.util;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class UploadUtils {
    public static Map<String, String> parseRequest(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletContext servletContext = request.getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = iterator.next();

                if (item.isFormField()) {
                    processFormField(item, map);
                } else {
                    processUploadFile(item, request, map);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }



    private static void processFormField(FileItem item, Map<String, String> map) {
        String fieldName = item.getFieldName();
        try {
            String value = item.getString("utf-8");
            System.out.println("fieldName: " + fieldName + "   value:" + value);

            map.put(fieldName, value);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private static void processUploadFile(FileItem item, HttpServletRequest request, Map<String, String> map) throws Exception {
        String fieldName = item.getFieldName();
        //对文件名进行改名，这样文件名就不会重复
        String name = item.getName();
        String uuid = UUID.randomUUID().toString();
        name = uuid + "-" + name;
        //把文件散列存储
        int hash = name.hashCode();
        String string = Integer.toHexString(hash);
        char[] chars = string.toCharArray(); // 1 2 3 4 5 6 A F
        String path = "image";

        //多级路径，路径太长可能加载不出来
//        for (char aChar : chars) {
//            //  image/1/2/3/4/5/6/A/F
//            path = path + "/" + aChar;
//        }

        //多级路径，路径较短
        for (int i = 0; i < chars.length / 2; i++) {
            path = path + "/" + chars[i];
        }

        //  image/1/2/3/4/5/6/A/F/1.jpg
        path = path + "/" + name;


//        System.out.println("fieldName:" + fieldName
//                + "  name:" + name
//                + "  contentType:" + contentType
//                + "    inMemory:" + inMemory
//                + "   size: " + size);

        map.put(fieldName, path);


        //保存到服务器本地
        File file = new File(request.getServletContext().getRealPath(path));
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        item.write(file);

    }
}



